from django.conf import settings
from django.forms.models import model_to_dict
from django.db.models import Avg, Sum, Count, Max, Min, Q, F
from django_filters import *
from django_filters.rest_framework import DjangoFilterBackend, FilterSet

from rest_framework import viewsets
from rest_framework import serializers
from rest_framework import versioning
from rest_framework.response import Response
from rest_framework.serializers import *
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator  # 验证器
from rest_framework.filters import SearchFilter, OrderingFilter


from iClouds.apidev import filter_views
from iClouds.Permissions import (
    OR,
    AllPermissions,
    MyPermissions,
    BoxPermissions,
    WeChatPermissions,
)
from iClouds.Authentication import (
    MyJWTAuthentication,
    BoxJWTAuthentication,
    WeChatJWTAuthentication,
)

from mysqldb.models import *
from mysqldb.serializers import ListDjangoFilterBackend
from mysqldb import redis as REDIS
from mysqldb.header import *


class NoneSerializer(serializers.Serializer):
    """无序列化"""

    class Meta:
        fields = "__all__"


class BarsDoLoginSerializer(serializers.Serializer):
    """登录用户"""

    username = CharField(max_length=255, required=True, help_text="用户名(手机、邮箱或openid)")
    password = CharField(max_length=255, required=True, help_text="用户密码")

    class Meta:
        fields = "__all__"


class BarsCorpListSerializer(serializers.ModelSerializer):
    """连锁列表"""

    class Meta:
        model = AllinpayPlacecorpList
        fields = "__all__"


class BarsStaffListSerializer(serializers.ModelSerializer):
    """员工列表"""

    id = IntegerField(label="ID", read_only=True)
    status = ReadOnlyField(help_text="状态")
    nicename = ReadOnlyField(help_text="昵称")
    basename = ReadOnlyField(help_text="姓名")
    icon = ReadOnlyField(help_text="头像")
    phone = ReadOnlyField(help_text="电话")
    idcode = ReadOnlyField(help_text="身份证")
    telent = ReadOnlyField(help_text="紧急联系人")
    openid = ReadOnlyField(help_text="openid")
    unid = ReadOnlyField(help_text="unionid")
    bankname = ReadOnlyField(help_text="户名")
    bankcard = ReadOnlyField(help_text="卡号")
    bankaddr = ReadOnlyField(help_text="开户行")
    bankcode = ReadOnlyField(help_text="联行号")
    created = ReadOnlyField(help_text="创建时间")
    modifed = ReadOnlyField(help_text="最近登录")

    class Meta:
        model = AllinpayStaffList
        fields = "__all__"


class BarsPlaceInfoSerializer(serializers.ModelSerializer):
    """场所列表"""

    id = IntegerField(label="ID", read_only=True)
    basename = ReadOnlyField(help_text="门店简称")
    name = ReadOnlyField(help_text="门店全称")
    telephone = ReadOnlyField(help_text="超级管理员(必填,手机号码)")
    phone = ReadOnlyField(help_text="场所联系电话")
    shopcode = ReadOnlyField(help_text="社会统一代码")
    licens = ReadOnlyField(help_text="上传营业执照")
    person = ReadOnlyField(help_text="企业法人")
    percode = ReadOnlyField(help_text="法人身份证号码")
    codea = ReadOnlyField(help_text="法人身份证正面")
    codeb = ReadOnlyField(help_text="法人身份证背面")
    titles = ReadOnlyField(help_text="经营场所照片")
    sheng = ReadOnlyField(help_text="省")
    shi = ReadOnlyField(help_text="市")
    xian = ReadOnlyField(help_text="县/区")
    addre = ReadOnlyField(help_text="详细地址")
    auth = ReadOnlyField(help_text="连锁ID")
    creattime = ReadOnlyField(help_text="创建时间")
    status = ReadOnlyField(help_text="场所状态")
    fee = ReadOnlyField(help_text="手续费")
    barcode = ReadOnlyField(help_text="场所编码")
    addr = ReadOnlyField(help_text="简拼")

    admin = SerializerMethodField()
    chain = SerializerMethodField()

    class Meta:
        model = AllinpayPlaceList
        fields = "__all__"

    def get_admin(self, attr):
        try:
            r = AllinpayStaffList.objects.get(phone=attr.telephone)
        except BaseException as err:
            return None
        else:
            return BarsPlaceInfoSerializer(r).data

    def get_chain(self, attr):
        try:
            r = AllinpayPlacecorpList.objects.get(id=attr.auth)
        except BaseException as err:
            return None
        else:
            return BarsCorpListSerializer(r).data


class ThisBarsPlaceStaffPostSerializer(serializers.Serializer):
    """自己在岗"""

    pid = IntegerField(help_text="场所ID")
    status = IntegerField(max_value=1, min_value=0, default=0, help_text="状态")

    class Meta:
        fields = "__all__"


class BarsPlaceStaffPostSerializer(serializers.ModelSerializer):
    """员工在岗"""

    id = IntegerField(
        validators=[UniqueValidator(queryset=AllinpayPlacestaffPost.objects.all())],
        help_text="员工入职绑定ID",
    )
    status = IntegerField(max_value=1, min_value=0, default=0, help_text="状态")
    current = DateTimeField(
        allow_null=True, required=False, default=timezone.now, help_text="时间"
    )

    class Meta:
        model = AllinpayPlacestaffPost
        fields = "__all__"


class BarsPlaceStaffSerializer(serializers.ModelSerializer):
    """场所员工列表"""

    id = IntegerField(label="ID", read_only=True)
    status = ReadOnlyField(help_text="状态")
    sid = ReadOnlyField(help_text="员工ID")
    pid = ReadOnlyField(help_text="场所ID")
    created = ReadOnlyField(help_text="入职时间")
    modifed = ReadOnlyField(help_text="离职时间")
    star = ReadOnlyField(help_text="星级")
    place = ReadOnlyField(help_text="场所端登录(转移到员工扩展信息)")
    mobile = ReadOnlyField(help_text="移动端登录(转移到员工扩展信息)")

    staff = SerializerMethodField()
    place = SerializerMethodField()
    onpost = SerializerMethodField()
    myrole = SerializerMethodField()

    class Meta:
        model = AllinpayPlacestaffList
        fields = "__all__"

    def get_staff(self, attr):
        try:
            r = AllinpayStaffList.objects.get(id=attr.sid)
        except BaseException as err:
            return None
        else:
            return BarsStaffListSerializer(r).data

    def get_place(self, attr):
        try:
            r = AllinpayPlaceList.objects.get(id=attr.pid)
        except BaseException as err:
            return None
        else:
            return BarsPlaceInfoSerializer(r).data

    def get_onpost(self, attr):
        try:
            r = AllinpayPlacestaffPost.objects.get(id=attr.id)
        except BaseException as err:
            return None
        else:
            return BarsPlaceStaffPostSerializer(r).data

    def get_myrole(self, attr):
        """获取职务(角色)"""
        r = AllinpayPlacestaffRole.objects.filter(
            pid=attr.pid, sid=attr.sid
        ).values_list("rid", flat=True)
        res = AllinpayPlaceroleList.objects.filter(id__in=r).values_list(
            "name", flat=True
        )
        return res


# print(repr(BarsPlaceStaffPostSerializer()))
